package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: zyx
 * @created: 2025-10-07-19:50
 * @description:
 */
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Override
    public PageResult<Course> page(String name, Integer subject, Integer target, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Course> rows = courseMapper.selectByPage(name, subject, target);
        PageInfo<Course> pageInfo = new PageInfo<>(rows);
        return PageResult.<Course>builder().total((int) pageInfo.getTotal()).rows(pageInfo.getList()).build();
    }

    @Override
    public Course getById(Integer id) {
        return courseMapper.selectById(id);
    }

    @Override
    public void update(Course course) {
        //使用hutool工具包进行参数校验
        boolean hasNullField = BeanUtil.hasNullField(course, "id", "description", "updateTime", "createTime");
        if (hasNullField) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.update(course);
    }

    @Override
    public void add(Course course) {
        //使用hutool工具包进行参数校验
        boolean hasNullField = BeanUtil.hasNullField(course, "id", "description", "updateTime", "createTime");
        if (hasNullField) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.add(course);
    }

    @Override
    public void delete(Integer id) {
        courseMapper.delete(id);
    }

    @Override
    public List<Course> list() {
        return courseMapper.list();
    }

    @Override
    public List<Course> listBySubject(Integer subject) {
        if (subject == null) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return courseMapper.listBySubject(subject);
    }
}
